package com.feizhi.common.search.index.action;

import java.io.Serializable;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.index.Term;
import org.springframework.stereotype.Component;

import com.feizhi.common.hash.MD5;
import com.feizhi.common.search.exception.SearchException;
import com.feizhi.common.search.index.IndexConstants;
import com.feizhi.common.search.index.LuceneWork;

/**
 * @author shuaqiu
 */
@Component
public class ExtDeleteIndexAction extends DeleteIndexAction {

    private static final Log LOG = LogFactory.getLog(ExtDeleteIndexAction.class);

    @Override
    public void performAction(final LuceneWork work) {
        final Class<?> entityType = work.getEntityType();
        final Serializable id = work.getId();
        try {

            final String typeName = entityType.getName();
            final String idStr = id.toString();

            try {
                LOG.trace( "Deleting " + work + " by id using an IndexWriter#deleteDocuments.");
                final String key = MD5.md5(typeName + idStr);
                final Term idTerm = new Term(IndexConstants.TYPE_KEY, key);
                writer.deleteDocuments(idTerm);
            } catch (final NoSuchAlgorithmException e) {
                LOG.error(e.getMessage(), e);
                super.performAction(work);
            }

        } catch (final Exception e) {
            final String message = "Unable to delete " + work + " in index.";
            throw new SearchException(message, e);
        }
    }

}
